const questionService = require('../../../../services/question');

Page({
  data: {
    questionId: '',
    questionData: {
      title: '',
      type: '',
      subject: '',
      difficulty: '',
      knowledgeList: [],
      options: [],
      answer: '',
      analysis: ''
    }
  },

  onLoad: function(options) {
    if (options.id) {
      this.setData({
        questionId: options.id
      });
      this.loadQuestionData(options.id);
    }
  },

  // 加载试题数据
  async loadQuestionData(questionId) {
    try {
      wx.showLoading({
        title: '加载中...'
      });

      const result = await questionService.getQuestionDetail(questionId);
      
      if (result.success) {
        // 处理知识点列表
        const knowledgeList = result.data.knowledge ? result.data.knowledge.split(',') : [];
        
        this.setData({
          questionData: {
            ...result.data,
            knowledgeList
          }
        });
      } else {
        wx.showToast({
          title: result.message || '加载失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('加载试题失败', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 编辑试题
  editQuestion() {
    wx.navigateTo({
      url: `/pages/teacher/question/edit/edit?id=${this.data.questionId}`
    });
  },

  // 删除试题
  deleteQuestion() {
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这道试题吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({
              title: '删除中...'
            });

            const result = await questionService.deleteQuestion(this.data.questionId);
            
            if (result.success) {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              });
              
              // 返回上一页
              setTimeout(() => {
                wx.navigateBack();
              }, 1500);
            } else {
              wx.showToast({
                title: result.message || '删除失败',
                icon: 'none'
              });
            }
          } catch (error) {
            console.error('删除试题失败', error);
            wx.showToast({
              title: '删除失败',
              icon: 'none'
            });
          } finally {
            wx.hideLoading();
          }
        }
      }
    });
  }
}); 